<?php
/**
 * Created by PhpStorm.
 * User: kb356
 * Date: 2016/12/2
 * Time: 13:49
 * 个推 推送接口
 */
namespace soa\gpush\gpush;

require_once dirname(__FILE__) . '/' . 'IGt.Push.php';
require_once dirname(__FILE__) . '/' . 'igetui/IGt.AppMessage.php';
require_once dirname(__FILE__) . '/' . 'igetui/IGt.APNPayload.php';
require_once dirname(__FILE__) . '/' . 'igetui/template/IGt.BaseTemplate.php';
require_once dirname(__FILE__) . '/' . 'IGt.Batch.php';
require_once dirname(__FILE__) . '/' . 'igetui/utils/AppConditions.php';

class gpush
{
    //获取连接配置
    static public function set_config($app)
    {
        //连接地址
        define('HOST', 'https://api.getui.com/apiex.htm');
        //应用配置  来源->个推官网
        if ($app == "weikuaidi") {
            define('APPKEY', 'ussToLHk4w8PhcYvt20K08');
            define('APPID', 'PxjoGrtGrPAvoLyPoDI1i6');
            define('MASTERSECRET', 'lCuDTA16z59nQkhbjUbtG9');
            define('APPLOGO', 'http://img.kuaidihelp.com/app/share.png');
        }
        elseif ($app == "vhome") {
            define('APPKEY', 'mKVNo4rFQR6Je7mNBkT9R2');
            define('APPID', 'TfjD1Zz9Vp9dn7HLtCX6F7');
            define('MASTERSECRET', 'CfuTzRofvh9yUX7fH1AG65');
            define('APPLOGO', 'http://img.kuaidihelp.com/www/app-merchant/wzg-logo.png');
        } else {
            define('APPKEY', 'QpcWnhGGji5lzYc18Zqxm');
            define('APPID', 'RTT5jRUiG08BP2LuTBSnj');
            define('MASTERSECRET', 'XBmnaijT5Y9hgex3G3dMc');
            define('APPLOGO', 'http://img.kuaidihelp.com/m/kdy-icon-40x40.png');
        }
    }
    //通过服务端设置ClientId的标签   可用定时任务 设置
    static public function setTag($app,$cid, $tags)
    {
        //分类推送 按标签（快递公司）推送
        self::set_config($app);
        $igt = new \IGeTui(HOST, APPKEY, MASTERSECRET);
        $tagList = array("{$tags}");
        $rep = $igt->setClientTag(APPID, $cid, $tagList);
        return $rep;
    }
    static public function getUserTags($app,$cid) {
        self::set_config($app);
        $igt = new \IGeTui(HOST,APPKEY,MASTERSECRET);
        $rep = $igt->getUserTags(APPID,$cid);
        return $rep;
    }
    //根据taskid 或日期 获取 推送数据 不可查当天
    static public function getPushMessageResult($app,$taskid,$date)
    {
        self::set_config($app);
        $igt = new \IGeTui(HOST, APPKEY, MASTERSECRET);
        if(!empty($taskid))
            $ret = $igt->getPushResult($taskid);
        else
        {
            $ret[] = $igt->queryAppUserDataByDate(APPID,$date);
            $ret[] = $igt->queryAppPushDataByDate(APPID, $date);

        }
        return $ret;
    }
    //单推接口
    static public function pushMessageToSingle($info,$platform)
    {
        self::set_config($info['app']);
        $igt = new \IGeTui(NULL, APPKEY, MASTERSECRET, false);
         //TransmissionTemplate:透传
        echo $platform;
        if($platform=='ios'){
            $template = self::IGtTransmissionTemplate($info);

        }else{
            $template = self::IGtNotificationTemplate($info);
        }
       // $template = self::IGtNotificationTemplate($info);
        //个推信息体
        $message = new \IGtSingleMessage();
        $message->set_isOffline(true);
        //是否离线
        $message->set_offlineExpireTime(3600 * 12 * 1000);
        //离线时间
        $message->set_data($template);
        //设置推送消息类型
        $message->set_PushNetWorkType(0);
        //设置是否根据WIFI推送消息，1为wifi推送，0为不限制推送
        //接收方
        $target = new \IGtTarget();
        $target->set_appId(APPID);
        $target->set_clientId($info['device']['client_id']);
        // $target->set_alias(Alias);（别名  每个cid  可以有一个别名）
        try {
            $rep = $igt->pushMessageToSingle($message, $target);
            return $rep;
        } catch (RequestException $e) {
            $requstId = e . getRequestId();
            $rep = $igt->pushMessageToSingle($message, $target, $requstId);
            return $rep;
        }
    }
    //群推接口
    static public function pushMessageToApp($info)
    {
        self::set_config($info['app']);

        if ($info['push_type'] == 'ios') {
            $rep = self::pushMessageToAppIos($info);
        }elseif($info['push_type'] == 'android'){
            $rep = self::pushMessageToAppAndroid($info);
        }else{
            $rep = self::pushMessageToAppIos($info);
            $rep = self::pushMessageToAppAndroid($info);
        }

        return $rep;

    }
    static public function pushMessageToAppIos($info){
        $igt = new \IGeTui(HOST, APPKEY, MASTERSECRET);
        $template = self::IGtTransmissionTemplate($info);
        //个推信息体
        //基于应用消息体

        $message = new \IGtAppMessage();

        $message->set_isOffline(true);
        $message->set_offlineExpireTime(12 * 3600 * 1000);
        //离线时间单位为毫秒，例，两个小时离线为3600*1000*2
        $message->set_data($template);
        $appIdList = array(APPID);
        //按地区设备标签不同推送
        if ($info['push_type'] == 'area') {
            $provinceList = array($info['limit']);
            $cdt = new \AppConditions();
            $cdt->addCondition(\AppConditions::REGION, $provinceList);
            $message->set_conditions($cdt->getCondition());
        } elseif ($info['push_type'] == 'ios' || $info['push_type'] == 'android') {
            $phoneTypeList = array("{$info['push_type']}");
            $cdt = new \AppConditions();
            $cdt->addCondition(\AppConditions::PHONE_TYPE, $phoneTypeList);
            $message->set_conditions($cdt->getCondition());
        } elseif ($info['push_type'] == 'brand') {
            $tagList = array($info['limit']);
            $cdt = new \AppConditions();
            $cdt->addCondition(AppConditions::TAG, $tagList);
            $message->set_conditions($cdt->getCondition());
        }
        $message->set_appIdList($appIdList);
        $rep = $igt->pushMessageToApp($message, "群推");
        return $rep;
    }
    static public function pushMessageToAppAndroid($info){
        $igt = new \IGeTui(HOST, APPKEY, MASTERSECRET);
        $template = self::IGtNotificationTemplate($info);
        //个推信息体
        //基于应用消息体

        $message = new \IGtAppMessage();

        $message->set_isOffline(true);
        $message->set_offlineExpireTime(12 * 3600 * 1000);
        //离线时间单位为毫秒，例，两个小时离线为3600*1000*2
        $message->set_data($template);
        $appIdList = array(APPID);
        //按地区设备标签不同推送
        if ($info['push_type'] == 'area') {
            $provinceList = array($info['limit']);
            $cdt = new \AppConditions();
            $cdt->addCondition(\AppConditions::REGION, $provinceList);
            $message->set_conditions($cdt->getCondition());
        } elseif ($info['push_type'] == 'ios' || $info['push_type'] == 'android') {
            $phoneTypeList = array("{$info['push_type']}");
            $cdt = new \AppConditions();
            $cdt->addCondition(\AppConditions::PHONE_TYPE, $phoneTypeList);
            $message->set_conditions($cdt->getCondition());
        } elseif ($info['push_type'] == 'brand') {
            $tagList = array($info['limit']);
            $cdt = new \AppConditions();
            $cdt->addCondition(AppConditions::TAG, $tagList);
            $message->set_conditions($cdt->getCondition());
        }
        $message->set_appIdList($appIdList);
        $rep = $igt->pushMessageToApp($message, "群推");
        return $rep;
    }


    //通知透传
    static public function IGtNotificationTemplate($info){
        $template =  new \IGtNotificationTemplate();
        $template->set_appId(APPID);//应用appid
        $template->set_appkey(APPKEY);//应用appkey
        $template->set_transmissionType(2);//透传消息类型
        $template->set_transmissionContent(json_encode($info['message']['custom_content']));//透传内容
        $template->set_title((string) $info['message']['custom_content']['title']);//通知栏标题
        $template->set_text((string) $info['message']['custom_content']['description']);//通知栏内容
        $template->set_logo(APPLOGO);//通知栏logo
        $template->set_isRing(true);//是否响铃
        $template->set_isVibrate(true);//是否震动
        $template->set_isClearable(true);//通知栏是否可清除
        // iOS推送需要设置的pushInfo字段
        $actionLocKey="ActionLockey";
        $badge = isset($info['badge'])?$info['badge']:1;
        $sound='';
        $payload='';
        $locKey='LocKey';
        $locArgs=array("locargs");
        $launchImage="launchimage";
        $message=(string) $info['message']['custom_content']['description'];
        $template ->set_pushInfo($actionLocKey,$badge,$message,$sound,$payload,$locKey,$locArgs,$launchImage);

        return $template;
    }

    //注：IOS离线推送需通过APN进行转发，需填写pushInfo字段，目前仅不支持通知弹框下载功能
    static public function IGtTransmissionTemplate($info)
    {
        $template = new \IGtTransmissionTemplate();
        $template->set_appId(APPID);
        //应用appid
        $template->set_appkey(APPKEY);
        //应用appkey
        $template->set_transmissionType(2);
        //透传消息类型
        $template->set_transmissionContent(json_encode($info['message']['custom_content']));
        //透传内容
        //APN高级推送
        $apn = new \IGtAPNPayload();
        $alertmsg = new \DictionaryAlertMsg();
        $alertmsg->body = (string) $info['message']['custom_content']['description'];
        $alertmsg->actionLocKey = "ActionLockey";
        $alertmsg->locKey = "LocKey";
        $alertmsg->locArgs = array("locargs");
        $alertmsg->launchImage = "launchimage";
        //        IOS8.2 支持
        $alertmsg->title = (string) $info['message']['custom_content']['title'];
        $alertmsg->titleLocKey = "TitleLocKey";
        $alertmsg->titleLocArgs = array("TitleLocArg");
        $apn->alertMsg = $alertmsg;
        $apn->badge = isset($info['badge'])?$info['badge']:1;
        $apn->sound = "";
        //添加自定义字段
//        foreach ($info['message']['custom_content'] as $k => $v) {
//            $apn->add_customMsg($k, $v);
//        }
       // $apn->contentAvailable = 1;
        $apn->category = "ACTIONABLE";
        $template->set_apnInfo($apn);
        return $template;
    }
}